<template>
	<el-drawer
		v-model="drawerVisible"
		@closed="resetForm(ruleFormRef)"
		:destroy-on-close="true"
		:close-on-click-modal="false"
		size="40%"
		:title="`${drawerProps.title}裁判员`"
	>
		<el-form ref="ruleFormRef" :rules="rules" :model="addOrUpdateForm" status-icon label-width="80" label-position="right">
			<el-form-item label="姓名" prop="name">
				<el-input placeholder="请输入" v-model="addOrUpdateForm.name"></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
				<el-input placeholder="请输入" v-model="addOrUpdateForm.phone"></el-input>
			</el-form-item>
			<el-form-item label="身份证号" prop="iDNumber">
				<el-input placeholder="请输入" v-model="addOrUpdateForm.iDNumber"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="resetForm(ruleFormRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit">保存</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
interface DrawerProps {
	title: string;
	isView: boolean;
	id: string | null;
	api?: any;
	getTableList?: () => void;
}
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: "",
	id: ""
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
	drawerProps.value = params;
	drawerVisible.value = true;
};
/**添加或更新常量 */
const addOrUpdateForm = ref({
	name: "",
	phone: "",
	iDNumber: ""
	// employeeId: ""
});

const rules = reactive<FormRules>({
	name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
	phone: [
		{ required: true, message: "手机号码不能为空", trigger: "blur" },
		{
			pattern: /^1[3456789]\d{9}$/,
			message: "请输入有效的手机号码",
			trigger: "blur"
		}
	],
	iDNumber: [
		{ required: true, message: "身份证不能为空", trigger: "blur" },
		{
			pattern: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/,
			message: "请输入有效的身份证号码",
			trigger: "blur"
		}
	]
});
// 关闭抽屉刷新数据
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	drawerVisible.value = false;
};
watch(
	() => drawerVisible.value,
	val => {
		if (!val) return;
		// getNewsById();
	}
);
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			await drawerProps.value.api!(addOrUpdateForm.value);
			ElMessage.success({ message: `${drawerProps.value.title}裁判员成功！` });
			drawerProps.value.getTableList!();
			drawerVisible.value = false;
		} catch (error) {
			console.log(error);
		}
	});
};
defineExpose({
	acceptParams
});
</script>
